package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.MvcArticle;
import cn.tedu._05mvcboot03.pojo.entity.User;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Validated
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserControllere {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        System.out.println("userLoginDTO = " + userLoginDTO);
         UserVO userVO=userMapper.selectByUsername(userLoginDTO.getUsername(),userLoginDTO.getPassword());
//        if ( userVO == null){//用户名错误
//            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
//        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user", userVO);
            return new JsonResult(StatusCode.OPERATION_SUCCESS);//登录成功
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }



    @ApiOperation(value = "发表文章功能")
    @PostMapping("article")
    public  JsonResult article(@RequestBody UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("UserArticleDTO"+userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){//未登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        MvcArticle mvcArticle = new MvcArticle();
        BeanUtils.copyProperties(userArticleDTO,mvcArticle);

        mvcArticle.setId(userVO.getId());
        userMapper.insertArticle(mvcArticle);
        return JsonResult.ok();

    }
    @ApiImplicitParam(name = "id", value = "文章编号", required = true, dataType = "int")
    @ApiOperation(value = " 查询指定文章功能")
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章ID必须在1-100之间") @RequestBody int id){
        log.debug("id = " + id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);

        return JsonResult.ok(articleVO);

    }
}
